import { Modal, notification } from "ant-design-vue";
import { mainAppRouter } from "../../router/index";
import { t } from "../../locale";
import store from "../../store";
import utils from "./utils";
import defaultSetting from "./defaultSetting";
import _ from "lodash";

// 登录页面
const LOGIN_PATH = "/user/login";
// 默认路由
let DEFAULT_PATH = "/index";
// 路由白名单
const WHITE_LIST = [LOGIN_PATH];

// 路由拦截器
mainAppRouter.beforeEach((to, from, next) => {
  setIsMobile(to);
  setIsIframe(to);
  const goNext = (to, from, next) => {
    if (to.query.token) {
      utils.setStorage("org_token", to.query.token).then(() => {
        delete to.query.token;
        next({
          ...to,
          replace: true,
        });
      });
    } else {
      const org_token = utils.getStorage("org_token");
      const user_token = utils.getStorage("user_token");
      if (org_token || user_token) {
        getUserInfo(to, next);
        if (to.name == "apps") {
          handleAppRoutesChange(to);
        }
      } else {
        if (WHITE_LIST.includes(to.path)) {
          //  免登录
          next();
        } else {
          // 进入登录页
          next({ path: LOGIN_PATH }); // , query: { redirect: to.fullPath }
        }
      }
    }
    if (!["apps", "iframes"].includes(to.name)) {
      getCurrentRoutesMenu(to);
    }
  }
  if (to.name == 'login') {
    store.dispatch("getConfig").then((res) => {
      if (store.getters.customSideMenu && res?.basic?.org_extra_config?.login_sso_url) {
        utils.setCookie("sso_referer", location.href);
        // 小梅沙 && res?.basic?.org_extra_config?.login_sso_url
        window.location.href = res.basic.org_extra_config.login_sso_url;
      } else {
        goNext(to, from, next)
      }
    })
  } else {
    goNext(to, from, next);
  }
});

let isCheckBuildsAndAutoCreate = true;
// 全局后置导航
mainAppRouter.afterEach((to, from) => {
  console.log("全局后置导航", to.path);
  //这里不接收next
  // 在非登录页面检查楼宇信息
  if (isCheckBuildsAndAutoCreate && to.path !== "/user/login") {
    isCheckBuildsAndAutoCreate = false;
  }
});

let setIsMobileFlag = false;
const setIsMobile = (to) => {
  if (setIsMobileFlag) {
    return;
  }
  if (
    (typeof to.query.from == "string" && to.query.from == "mobile") ||
    (Array.isArray(to.query.from) && to.query.from.includes("mobile"))
  ) {
    store.dispatch("setIsMobile", true);
  }
  setIsMobileFlag = true;
};

let setIsIframeFlag = false;
const setIsIframe = (to) => {
  if (setIsIframeFlag) {
    return;
  }
  if (
    (typeof to.query.from == "string" && to.query.from == "iframe") ||
    (Array.isArray(to.query.from) && to.query.from.includes("iframe"))
  ) {
    store.dispatch("setIsIframe", true);
  }
  setIsIframeFlag = true;
};

//  是否已经获取用户信息了
function getUserInfo(to, next) {
  const userInfo = store.getters.userInfo;
  if (userInfo && Object.keys(userInfo).length) {
    utils.consoleInfo(to.name, "主应用即将跳转");
    getUserInfoAfter(to, next);
  } else {
    store
      .dispatch("GetUserInfo")
      .then((res) => {
        // console.log("res", res);
        if (
          res.org_info &&
          res.org_info.homeUrl &&
          res.org_info.homeUrl.url &&
          (to.path == "" || to.path == "/index")
        ) {
          let url = res.org_info.homeUrl.url;
          url = decodeURIComponent(url || "/index");
          utils.goUrl(url, "replace");
        } else {
          if (res.user_info && res.user_info.org_id) {
            getUserInfoAfter(to, next);
          } else {
            store.dispatch("Logout");
          }
        }
      })
      .catch((err) => {
        Modal.warning({
          content: err.msg || "系统繁忙，请稍后再试（profile）",
          centered: true,
          onOk: () => {
            // 失败时，获取用户信息失败时，调用登出，来清空历史保留信息
            process.env.NODE_ENV === "production" &&
              store.dispatch("Logout");
          },
        });
      });
  }
}

function getUserInfoAfter(to, next) {
  const orgInfo = store.getters.orgInfo;
  if (orgInfo.homeUrl && orgInfo.homeUrl.url) {
    DEFAULT_PATH = orgInfo.homeUrl.url;
    console.log("to.name", to.name);
    const currentApp = store.getters.currentApp;
    if (to.name == "apps" && !currentApp.id) {
      const appList = store.getters.appList;
      const app = appList.find((item) => item.app_micro == orgInfo.homeUrl.app);
      if (app) {
        store.dispatch("SetCurrentApp", app).then(() => {
          next();
        });
        return;
      }
    }
  }
  if (to.path === LOGIN_PATH) {
    next({ path: DEFAULT_PATH });
  } else {
    next();
  }
}

// 进入的目标与缓存的路由不匹配 重新设置菜单选中
const getCurrentRoutesMenu = (to) => {
  const currentTopMenu = store.getters.currentTopMenu;
  const userMenu = store.getters.userMenu;
  if (!userMenu.length) {
    setTimeout(() => {
      getCurrentRoutesMenu(to);
    }, 200);
    return;
  }
  if (!currentTopMenu.alias || currentTopMenu.alias != to.name) {
    let result = userMenu.find((it) => it.alias == to.name && !it.param);
    if (result) {
      // 进入的是顶级菜单
      result.alias != "setting" && store.dispatch("SetCurrentTopMenu", result);
    } else {
      const menuList = store.getters.menuList;
      const menu = menuList.find((item) => item.alias == to.name);
      if (menu) {
        setCurrentMenu(menu);
      }
    }
  }
};
const setCurrentMenu = (menu) => {
  const menuList = store.getters.menuList;
  const parenMenu = menuList.find((it) => it.id == menu.parent_id);
  if (parenMenu && parenMenu.parent_id == 0) {
    const userMenu = store.getters.userMenu;
    let topMenu =
      userMenu.find((it) => it.alias == parenMenu.alias) || parenMenu;
    if (topMenu.alias != "setting") {
      store.dispatch("SetCurrentTopMenu", topMenu);
    }
    return;
  } else {
    setCurrentMenu(parenMenu, parent);
  }
};

function handleAppRoutesChange(to) {
  const {
    params: { afterApps },
    path,
  } = to;
  const belongApp = afterApps.split("/")[0];
  if (
    window[defaultSetting.shareSessionName] &&
    window[defaultSetting.shareSessionName][`${belongApp}_routes`]
  ) {
    const appRoutes =
      window[defaultSetting.shareSessionName][`${belongApp}_routes`];
    const result = getMenuByRoute(appRoutes, path);
    // const nameList = store.getters.menuNameList;

    if (
      result
      // &&
      // (!nameList.length ||
      //   nameList.includes(result.name) ||
      //   (result.meta &&
      //     nameList.includes(getPermisson(nameList, result.meta.permisson))))
    ) {
      const parent = getRouteParent(belongApp, result, to);
      if (parent) {
        store.getters.currentTopMenu.alias != parent.alias &&
          store.dispatch("SetCurrentTopMenu", parent);
        store.dispatch("SetCurrentSubMenuName", result);
      }
    }
  } else {
    setTimeout(() => {
      handleAppRoutesChange(to);
    }, 300);
  }
}

const getMenuByRoute = (appRoutes, path, parentPath = "") => {
  for (let menu of appRoutes) {
    const currentPath = `${parentPath ? parentPath + "/" : ""}${menu.path}`;
    // 兼容动态路由
    if (currentPath.indexOf(":") !== -1) {
      let currentArr = currentPath.split("/");
      let pathArr = path.split("/");
      let _current = _.cloneDeep(currentArr);
      currentArr.forEach((item, index) => {
        if (item.indexOf(":") !== -1) {
          _current[index] = pathArr[index];
        }
      });
      if (_current.join("/") == path) {
        return menu;
      }
    } else if (currentPath == path) {
      return menu;
    }
    if (menu.children && menu.children.length) {
      const result = getMenuByRoute(menu.children, path, currentPath);
      if (result) {
        return result;
      }
    }
  }
};

const getRouteParent = (appName, r, to) => {
  const appMenu = store.getters.appMenu;
  if (!Object.keys(appMenu).length) {
    setTimeout(() => {
      handleAppRoutesChange(to);
    }, 500);
    return false;
  }
  if (appMenu && appMenu[appName]) {
    const appRoute = appMenu[appName].find((item) => item.alias == r.name);
    if (appRoute) {
      const userMenu = store.getters.userMenu;
      const parentRoute = userMenu.find(
        (item) => item.id == appRoute.parent_id
      );
      if (parentRoute) {
        return parentRoute;
      }
    }
  }
  return false;
};
